package top.bulk.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import top.bulk.entity.UserEntity;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.Validator;
import javax.validation.constraints.Min;
import java.util.Set;

/**
 * 测试在service层面直接校验参数的使用
 *
 * @author 散装java
 * @version 1.0.0
 * @date 2024-06-10
 */
@Service
@Slf4j
@Validated
public class UserService {
    @Resource
    Validator validator;

    public String get(@Min(value = 1L, message = "编号必须大于 0") Integer id) {
        log.info("[get][id: {}]", id);
        return "ok";
    }

    public void add(@Valid UserEntity user) {
        log.info("[add][user: {}]", user);
    }

    /**
     * 编程式校验
     */
    public void add2(UserEntity user) {
        Set<ConstraintViolation<UserEntity>> res = validator.validate(user);
        if (!res.isEmpty()) {
            throw new ConstraintViolationException(res);
        }

        // 执行业务操作
    }

    public void add3(UserEntity user) {
        // Spring 的 validator 的校验方式
        // BindingResult bindingResult = new BeanPropertyBindingResult(user, "user");
        // validator.validate(user, bindingResult);
        // if (bindingResult.hasErrors()) {
        //     bindingResult.getFieldErrors().forEach(error -> {
        //         System.out.println("Field: " + error.getField() + ", Error: " + error.getDefaultMessage());
        //     });
        // } else {
        //     System.out.println("验证通过");
        // }
    }
}
